﻿using BarcodeDelay.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class TransferHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListWeightBarcodes = new ArrayList();
        public event Action weightEvent;

        private static TransferHelperGen instance;
        public static TransferHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new TransferHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string anayType)
        {
            try
            {
                initLog();
                m_arListWeightBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListWeightBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseTransfer));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }



        public void parseTransfer(object arListBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";
                StoParams.Instance.resMsg = "";
                ArrayList arListUseFulBarcodes = new ArrayList();
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                //foreach (string strBarCode in (ArrayList)arListBarcodes)
                {
                    string strBarCode = parcelBean.wayBill;
                    intProcess++;
                    ArrayList arListAllGXTask = new ArrayList();
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";
                    if (!UtilityHelp.Instance.resetToken(strBarCode,out pickName,out orderSource,out curSiteToken,out customerName))
                    {
                        if (curSiteToken == "")
                        {
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                            continue;
                        }

                        System.Threading.Thread.Sleep(50);
                        logHelp.LogHelper.Instance.writeLog(strBarCode + " 发件网点 " + pickName + " 非我司单号  无法处理");
                        StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                        continue;
                        
                    }
                    parcelBean.customerName = customerName;
                    ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(strBarCode, out httpRes, arListAllGXTask);
                    if (!httpRes.Contains("成功"))
                    {
                        logHelp.LogHelper.Instance.writeLog(strBarCode + " 请求失败 "+ httpRes);
                        StoParams.Instance.resMsg = StoParams.Instance.resMsg+" "+httpRes;
                        System.Threading.Thread.Sleep(100);
                        resMsg = "请求失败";
                        StoParams.Instance.htResWechat[strBarCode] = resMsg;
                        continue;
                    }
                    if (httpRes.Contains("成功")&& arListRoadMap.Count==0)
                    {
                        logHelp.LogHelper.Instance.writeLog(strBarCode + " " + "快件未揽收");
                        resMsg = "快件未揽收";
                        StoParams.Instance.htResWechat[strBarCode] = resMsg;
                        continue;
                    }
                    
                    arListUseFulBarcodes.Add(strBarCode);

                }

                string transferMsg = "";
                transferParcel(arListUseFulBarcodes, out transferMsg);
                foreach(string barcode in arListUseFulBarcodes)
                {
                    StoParams.Instance.htResWechat[barcode] = transferMsg;
                }

                Random ran = new Random();




            }
            catch (Exception ex)
            {
                logHelp.LogHelper.Instance.writeLog(" 转运异常 " + ex.ToString());
            }
           


        }


        private bool transferParcel(ArrayList arListBarcodes, out string msg)
        {
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://opa.jtexpress.com.cn/opa/smart/scan/uploadLoadingSendData";
                JObject jObj = new JObject();

                //string listID = System.Guid.NewGuid().ToString().Replace("-", "").ToLower();

                JArray jarry = new JArray();
                foreach (string strCurBarcode in arListBarcodes)
                {
                    jObj["listId"] = System.Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    jObj["waybillId"] = strCurBarcode;
                    jObj["scanType"] = "1";
                    jObj["packageNumber"] = "";
                    jObj["scanTime"] = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    jObj["scanPda"] = "CS0000000001001";
                    jObj["transportTypeCode"] = "02";
                    jObj["taskCode"] = StoParams.Instance.taskCode;
                    jObj["nextStopCode"] = StoParams.Instance.nextStaCode;                                       
                    jarry.Add(jObj);
                }


                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jarry);
                string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, "returnAndForwardMaintain", MemberInfo.Instance.lanshoutoken);
                //string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, "returnAndForwardMaintain", "7af17dca894c46a8835395dbe45f22f3");
                if (!resMsg.Contains("请求成功"))
                {
                    logHelp.LogHelper.Instance.writeLog("中转失败，返回信息：" + resMsg);
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];
                    msg = "以上单号中转失败" + msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "以上单号中转成功";
                    res = true;
                    return true;
                }


                //jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
            }
            catch (Exception ex)
            {
                msg = "以上单号中转失败" + ex.ToString();
                return false;
            }


            return res;
        }


        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
